package com.erp.common;

import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 全局异常处理
 */
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 处理shiro框架异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(ShiroException.class)
    public R<String> doHandleShiroException(
            ShiroException e) {
        if (e instanceof UnknownAccountException) {
            return R.error("账户不存在");
        } else if (e instanceof LockedAccountException) {
            return R.error("账户已被禁用");
        } else if (e instanceof IncorrectCredentialsException) {
            return R.error("密码不正确");
        } else if (e instanceof AuthorizationException) {
            return R.error("没有此操作权限");
        } else {
            return R.error("系统维护中");
        }
    }

    /**
     * 异常处理方法
     *
     * @return
     */
    @ExceptionHandler(EmptyResultDataAccessException.class)
    public R<String> exceptionHandler(EmptyResultDataAccessException ex) {
        log.error(ex.getMessage());

        String[] split = ex.getMessage().split(" ");
        String msg = "id为" + split[6] + "不存在";
        return R.error(msg);
    }

    /**
     * 异常处理方法
     *
     * @return
     */
    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex) {
        log.error(ex.getMessage());

        return R.error(ex.getMessage());
    }
}
